package com.bleem.ds.xinshou.a02;

/**
 * @author SuYanchun
 * @since 2024-08-07 下午1:40
 */
public class RangeSum {
    private final int[] preSum;

    public RangeSum(int[] arr) {
        this.preSum = new int[arr.length];
        preSum[0] = arr[0];
        for (int i = 1; i < arr.length; i++) {
            preSum[i] = preSum[i - 1] + arr[i];
        }
    }

    public int rangeSum(int left, int right) {
        if (left > right || right > preSum.length - 1) {
            throw new ArrayIndexOutOfBoundsException("左右索引错误");
        }
        return left == 0 ? preSum[right] : (preSum[right] - preSum[left - 1]);
    }


    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 5, 6, 8, 2};
        RangeSum rangeSum = new RangeSum(arr);
        System.out.println("3~3:" + rangeSum.rangeSum(3, 3));
        System.out.println("2~5:" + rangeSum.rangeSum(2, 7));
    }
}
